﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace usbburn
{
    public partial class Progress : Form
    {
        List<Job> m_list = new List<Job>();
        Thread m_th;
        bool m_cancel;

        public Progress()
        {
            InitializeComponent();
        }

        public void AddJob(Job j)
        {
            m_list.Add(j);
        }

        private void Progress_Load(object sender, EventArgs e)
        {
            //DialogResult = DialogResult.OK;

            progressBar1.Value = 0;
            progressBar1.Minimum = 0;
            progressBar1.Maximum = 100;

            backgroundWorker1.WorkerReportsProgress = true;
            backgroundWorker1.WorkerSupportsCancellation = true;
            backgroundWorker1.RunWorkerAsync();
        }

        private void cancel_Click(object sender, EventArgs e)
        {
            backgroundWorker1.CancelAsync();
            cancel.Enabled = false;
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            foreach (Job j in m_list)
            {
                Job.Info i = j.GetJobInfo();

                long pos = 0;
                while ((pos = j.Poll()) < i.Max)
                {
                    worker.ReportProgress((int)(pos / (float)i.Max * 100), i.Name);
                    if (worker.CancellationPending)
                        return;
                }
            }
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage;
            Text = (string)e.UserState;
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if(e.Error!=null)
                throw e.Error;

            if (cancel.Enabled == false)
                DialogResult = DialogResult.Cancel;
            else
                DialogResult = DialogResult.OK;
        }
    }
}
